package com.yfp.common.log.service;

import cn.hutool.json.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.yfp.common.core.constant.SecurityConstants;
import com.yfp.common.core.web.domain.AjaxResult;
import com.yfp.common.redis.service.RedisService;
import com.yfp.system.api.RemoteLogService;
import com.yfp.system.api.RemoteUserService;
import com.yfp.system.api.domain.SysOperLog;
import com.yfp.system.api.domain.SysOperationLog;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * 异步调用日志服务
 *
 *
 */
@Service
@Slf4j
public class AsyncLogService
{
    @Resource
    private RemoteLogService remoteLogService;
    @Resource
    private RemoteUserService remoteUserService;
    @Resource
    private RedisService redisService;

    /**
     * 保存系统日志记录
     */
    @Async
    public void saveSysLog(SysOperLog sysOperLog) throws Exception
    {
        remoteLogService.saveLog(sysOperLog, SecurityConstants.INNER);
    }

    /**
     * 添加其他日志
     * @param sysOperationLog
     */
    public void addOperationLog(SysOperationLog sysOperationLog){

        String account = sysOperationLog.getAccount();
        if (StringUtil.isEmpty(sysOperationLog.getAccount())) {
            Object cacheObject = redisService.getCacheObject("device:login:" + sysOperationLog.getMachineId());
            if (null != cacheObject) {
                account = cacheObject.toString();
            }
        }
        if (StringUtil.isEmpty(account)) {
            return;
        }
        sysOperationLog.setAccount(account);
        AjaxResult byUserName = remoteUserService.getByUserName(account);

        Object data = byUserName.get("data");

        if (null != data) {
            JSONObject jsonObject = new JSONObject(data);
            String nickName = jsonObject.get("nickName").toString();
            if (!StringUtil.isEmpty(nickName)) {
                sysOperationLog.setUserName(nickName);
            }
        }

        log.info("远程调用新增其他操作日志，参数:{}",sysOperationLog);
        remoteLogService.addOperationLog(sysOperationLog, SecurityConstants.INNER);

    }


}
